<?php
class PhotoGalleryModel{
	
#TODO settings
	protected function zapiszUstawienia(){
		global $config;
		foreach ($config->ustawienia_photogallery as $id => $wartosc) {
			$id__ = tools::__adodb('getOne',"SELECT id  FROM ".PGSETTIN." WHERE id = ".tools::__mres($id),true,$this->db); 
			if($id == $id__){
				tools::__adodb("exec","UPDATE ".PGSETTIN." SET wartosc = ".tools::__mres($wartosc)." WHERE id = ".tools::__mres($id),true,$this->db);
			}else{
				tools::__adodb("exec","INSERT INTO ".PGSETTIN." (id, wartosc) VALUES (".tools::__mres($id).",".tools::__mres($wartosc).");",true,$this->db);
			}
		}
	}
		
	protected function pobierzUstawienia(){	
		$q__ = "SELECT id, wartosc FROM ".PGSETTIN;
		return tools::__adodb('getAssoc',$q__,true,$this->db);
	}
	
	protected function wyzerujUstawieniaPG(){
		return tools::__adodb('exec',"DELETE FROM ".PGSETTIN,true,$this->db);
	}
	
#TODO categorry
	protected function zapiszNowaKategorie(){
		global $config;
		$q__ = "INSERT INTO ".PGCATEGO." (pgID,pgPage,pgStatus,pgLp) 
			VALUES (NULL,".tools::__mres($config->page).",0,0)";
		tools::__adodb('exec',$q__,true,$this->db);
		
		$pgID = $this->db->lastInsertId();
		if(is_array($config->pgNazwa)){
			foreach ($config->pgNazwa as $lang => $pgNazwa) {
				$pgOPis__ = (isset($config->pgOpis[$lang])) ? $config->pgOpis[$lang] : '';
				$q__ = "INSERT INTO ".PGCATELA." (pgID,pgLang,pgNazwa,pgOpis) 
					VALUES (".tools::__mres($pgID).",'{$lang}',".tools::__mres($pgNazwa).",".tools::__mres($pgOPis__).")";
				tools::__adodb('exec',$q__,true,$this->db);				
			}
		}else{
			$q__ = "INSERT INTO ".PGCATELA." (pgID,pgLang,pgNazwa) 
				VALUES (".tools::__mres($pgID).",'{$config->__lang}',".tools::__mres($config->pgNazwa).")";
			tools::__adodb('exec',$q__,true,$this->db);
		}	
		return $pgID;
	}
	
	protected function zapiszEdytowanaKategorie(){
		global $config;
		
		if(is_array($config->pgNazwa)){
			foreach ($config->pgNazwa as $lang => $kateg) {
				$q__ = "SELECT COUNT(*) FROM ".PGCATEGO." a 
					LEFT JOIN ".PGCATELA." b ON b.pgID = a.pgID 
					WHERE b.pgLang = '{$lang}' AND a.pgID = '{$config->pgID}'";
				$istnieje = tools::__adodb('getOne',$q__,true,$this->db);
				if($istnieje == 1){
					$q__ = "UPDATE ".PGCATELA." SET pgNazwa = ".tools::__mres($kateg)."
						WHERE pgID = ".tools::__mres($config->pgID)." AND pgLang = ".tools::__mres($lang);
					tools::__adodb('exec',$q__,true,$this->db);	
				}else{
					$q__ = "INSERT INTO ".PGCATELA." (pgID,pgLang,pgNazwa) 
					VALUES (".tools::__mres($config->pgID).",'{$lang}',".tools::__mres($kateg).")";
					tools::__adodb('exec',$q__,true,$this->db);		
				}
			}
			
		}else{
			$q__ = "UPDATE ".PGCATELA." SET pgNazwa = ".tools::__mres($config->pgNazwa)."
				WHERE pgID = ".tools::__mres($config->pgID)." AND pgLang = ".tools::__mres($config->pgLang);
			tools::__adodb('exec',$q__,true,$this->db);
		}	

		if(is_array($config->pgOpis)){
				foreach ($config->pgOpis as $lang => $Opis__) {
					$q__ = "SELECT COUNT(*) FROM ".PGCATEGO." a 
						LEFT JOIN ".PGCATELA." b ON b.pgID = a.pgID 
						WHERE b.pgLang = '{$lang}' AND a.pgID = '{$config->pgID}'";
					$istnieje = tools::__adodb('getOne',$q__,true,$this->db);
					if($istnieje == 1){
						$q__ = "UPDATE ".PGCATELA." SET pgOpis = ".tools::__mres($Opis__)."
							WHERE pgID = ".tools::__mres($config->pgID)." AND pgLang = ".tools::__mres($lang);
						tools::__adodb('exec',$q__,true,$this->db);	
					}else{
						$q__ = "INSERT INTO ".PGCATELA." (pgID,pgLang,pgOpis) 
						VALUES (".tools::__mres($config->pgID).",'{$lang}',".tools::__mres($Opis__).")";
						tools::__adodb('exec',$q__,true,$this->db);		
					}
				}
			}
	}
	
	protected function pobiezKategorie($pgID = null,$lang=null, $pgStatus=''){
		global $objSession,$config;
		if(is_null($pgID)){
			// lista wszystkich kategorii dla domyslnego jezyka
			$page__ = ( $config->__isset('page') ) ? $config->page : $_REQUEST['page'];
			if ( $objSession->IsLoggedIn()  && $objSession->GetUserData("stanowisko") == 'a'){			
				$q__ = "SELECT a.*, b.pgNazwa, b.pgLang, b.pgOpis FROM ".PGCATEGO." a 
					LEFT JOIN ".PGCATELA." b ON b.pgID = a.pgID 
					WHERE b.pgLang = '{$config->__lang}' 
					AND a.pgPage = ".tools::__mres($page__)." ORDER BY a.pgLp";
			}else{
				$q__ = "SELECT a.*, b.pgNazwa, b.pgLang, b.pgOpis FROM ".PGCATEGO." a 
					LEFT JOIN ".PGCATELA." b ON b.pgID = a.pgID 
					WHERE b.pgLang = '{$config->__lang}' 
					AND a.pgPage = ".tools::__mres($page__)."
					AND a.pgStatus = 0 	ORDER BY a.pgLp"; 				
			}
			return tools::__adodb('getAll',$q__,true,$this->db);
		}else{
			if  ($lang != null){
				// kategoria dla wybranego jezyka
				$q__ = "SELECT a.*, b.pgNazwa, b.pgOpis, b.pgLang FROM ".PGCATEGO." a 
					LEFT JOIN ".PGCATELA." b ON b.pgID = a.pgID 
					WHERE b.pgLang = '{$lang}' AND a.pgID = '$pgID'";
				return tools::__adodb('getRow',$q__,true,$this->db);
			}else{
				// kategoria wiele jezykow
				$q__ = "SELECT a.*, b.pgNazwa, b.pgOpis, b.pgLang FROM ".PGCATEGO." a 
					LEFT JOIN ".PGCATELA." b ON b.pgID = a.pgID 
					WHERE a.pgID = '$pgID'";
				return tools::__adodb('getAll',$q__,true,$this->db);							
			}
		}
	}
	
	protected function pgLpUp($id_kategoria=null){
		$q__ = "SELECT pgLp,pgID FROM ".PGCATEGO." WHERE pgID = {$id_kategoria}";
		$curent_row = tools::__adodb('getRow',$q__,true,$this->db);
		$curent_lp__ = $curent_row['pgLp'];		
		$new_lp__ =  $curent_lp__- 1;
		if ($curent_lp__ > 1){
			if(tools::__adodb('exec',"UPDATE ".PGCATEGO." SET pgLp={$curent_lp__} WHERE pgLp = {$new_lp__}",true,$this->db))
				tools::__adodb('exec',"UPDATE ".PGCATEGO." SET pgLp={$new_lp__} WHERE pgID = {$id_kategoria}",true,$this->db);
		}		
	}
	
	protected function pgLpDown($id_kategoria=null){
		$curent_row = tools::__adodb('getRow',"SELECT pgLp  FROM ".PGCATEGO." WHERE pgID = {$id_kategoria}",true,$this->db);
		$curent_lp__ = $curent_row['pgLp'];
		$max_lp__ = tools::__adodb('getOne',"SELECT MAX(pgLp) FROM ".PGCATEGO ,true,$this->db);
		$new_lp__ = (is_numeric($curent_lp__) && $curent_lp__ == 0) ? $max_lp__ + 1  : $curent_lp__+ 1;
		if ($curent_lp__ < $max_lp__ || $max_lp__ == 0 || $curent_lp__ == 0){
			if(tools::__adodb('exec',"UPDATE ".PGCATEGO." SET pgLp={$curent_lp__} WHERE pgLp = {$new_lp__}",true,$this->db))
				tools::__adodb('exec',"UPDATE ".PGCATEGO." SET pgLp={$new_lp__} WHERE pgID = {$id_kategoria}",true,$this->db);
		}		
	}

	protected function phLpUp($phID_=null){
		$q__ = "SELECT phLp,pgID FROM ".PGPHOTOS." WHERE phID = {$phID_}";
		$curent_row = tools::__adodb('getRow',$q__,true,$this->db);
		$curent_lp__ = $curent_row['phLp'];		
		$new_lp__ =  $curent_lp__- 1;
		if ($curent_lp__ > 1){
			if(tools::__adodb('exec',"UPDATE ".PGPHOTOS." SET phLp={$curent_lp__} WHERE phLp = {$new_lp__}",true,$this->db))
				tools::__adodb('exec',"UPDATE ".PGPHOTOS." SET phLp={$new_lp__} WHERE phID = {$phID_}",true,$this->db);
		}		
	}
	
	protected function phLpDown($phID_=null){
		$curent_row = tools::__adodb('getRow',"SELECT phLp,pgID  FROM ".PGPHOTOS." WHERE phID = {$phID_}",true,$this->db);
		$curent_lp__ = $curent_row['phLp'];
		$max_lp__ = tools::__adodb('getOne',"SELECT MAX(phLp) FROM ".PGPHOTOS ,true,$this->db);
		$new_lp__ = (is_numeric($curent_lp__) && $curent_lp__ == 0) ? $max_lp__ + 1  : $curent_lp__+ 1;
		if ($curent_lp__ < $max_lp__ || $max_lp__ == 0 || $curent_lp__ == 0){
			if(tools::__adodb('exec',"UPDATE ".PGPHOTOS." SET phLp={$curent_lp__} WHERE phLp = {$new_lp__}",true,$this->db))
				tools::__adodb('exec',"UPDATE ".PGPHOTOS." SET phLp={$new_lp__} WHERE phID = {$phID_}",true,$this->db);
		}		
	}
	protected function zliczAktywneGalerie(){
		global $config;
		$count_ =  tools::__adodb('getOne',"SELECT Count(*) FROM ".PGCATEGO." WHERE pgStatus = 0 AND pgPage = '{$config->page}'",true,$this->db);
		return $count_;
	}
	
	protected function domyslnaGaleria(){
		global $config;
		$count_ =  tools::__adodb('getOne',"SELECT Min(pgID) FROM ".PGCATEGO." WHERE pgStatus = 0 AND pgPage = '{$config->page}'",true,$this->db);
		return $count_;
	}
	
	protected function zliczZdjeciaGalerii($pgID){
		$count_ =  tools::__adodb('getOne',"SELECT Count(*) FROM ".PGPHOTOS." WHERE pgID = {$pgID}",true,$this->db);
		return $count_;
	}


	protected function pobiezJednaGalerie($pgID = null,$lang=null, $phStatus=''){
		if  ($lang != null){
			// galeria dla wybranego jezyka
			$q__ = "SELECT a.*, b.phNazwa, b.phOpis, b.phLang, b.phUrl FROM ".PGPHOTOS." a 
				LEFT JOIN ".PGPHOTLA." b ON b.phID = a.phID 
				WHERE b.phLang = '{$lang}' AND a.pgID = '$pgID' {$phStatus}  
				ORDER BY a.phLP";
			return tools::__adodb('getAll',$q__,true,$this->db);
		}else{
			// galeria wiele jezykow
			$q__ = "SELECT a.*, b.phNazwa, b.phOpis, b.phLang, b.phUrl FROM ".PGPHOTOS." a 
				LEFT JOIN ".PGPHOTLA." b ON b.phID = a.phID 
				WHERE a.pgID = '$pgID' ORDER BY a.phLP";
			return tools::__adodb('getAll',$q__,true,$this->db);							
		}

	}

	protected function pobiezJednoZdjecie($phID = null,$lang=null){
		if  ($lang != null){
			// zdjecie dla jednego jezyka
			$q__ = "SELECT a.*, b.phNazwa, b.phOpis, b.phLang, b.phUrl FROM ".PGPHOTOS." a 
				LEFT JOIN ".PGPHOTLA." b ON b.phID = a.phID 
				WHERE b.phLang = '{$lang}' AND a.phID = '$phID'";
			$result = tools::__adodb('getRow',$q__,true,$this->db);
			return (is_array($result)) ? $result : false;
		}else{
			// galeria wiele jezykow
			$q__ = "SELECT a.*, b.phNazwa, b.phOpis, b.phLang, b.phUrl FROM ".PGPHOTOS." a 
				LEFT JOIN ".PGPHOTLA." b ON b.phID = a.phID 
				WHERE a.phID = '$phID'";
			$result = tools::__adodb('getAll',$q__,true,$this->db);
			return (is_array($result)) ? $result : false;							
		}

	}
	
	protected function pobiezIkonkeKategorii($pgID = null, $limit=null){
		global $config;
			$limit2 = $limit+1;
			$q__ = "SELECT a.*, b.phNazwa, b.phOpis, b.phLang FROM ".PGPHOTOS." a 
				LEFT JOIN ".PGPHOTLA." b ON b.phID = a.phID 
				WHERE b.phLang = '{$config->__lang}' AND a.pgID = '$pgID' LIMIT $limit,$limit2";
			return tools::__adodb('getRow',$q__,true,$this->db);
	}
		
	protected function zapiszPlikiGalerii($pgID){
		global $config;
		$lp__ =  tools::__adodb('getOne',"SELECT Max(phLp) FROM ".PGPHOTOS." WHERE pgID = {$pgID}",true,$this->db);


		// zapis pliku i danych
		foreach ($_FILES as $fieldName => $file) {	
		
			if ($file['size'] <= $this->maxfilesize && $file['error'] == 0 ) {
				$q = "INSERT INTO ".PGPHOTOS." (phID,pgID,phFile,phStatus,phLp) 
				VALUES (NULL,{$pgID}, '{$pgID}_".tools::__link($file['name'])."',0,".tools::__mres($lp__).")";
				tools::__adodb('exec',$q,true,$this->db);
				$phID = $this->db->lastInsertId();
				$this->zapiszDanePlikuPhotoGallery($phID);
				$up=move_uploaded_file($file['tmp_name'],  "{$this->PhotoGalleryRoot}{$pgID}_".tools::__link($file['name']) );
			}else{
				$up = false;
			}
			
			$lp__++;
		}

	}
	
	
	protected function podmienPlikGalerii(){
		global $config;
		// zapis pliku i danych
		
		foreach ($_FILES as $fieldName => $file) {
		
			if ($file['size'] <= $this->maxfilesize && $file['size'] > 0 && $file['error'] == 0 ) {
				$this->usunPlikiZdjecia($config->phFileOld);
				$q = "UPDATE ".PGPHOTOS." SET phFile = '".tools::__mres($config->pgID,false,true)."_".tools::__link($file['name'])."' WHERE phID = ".tools::__mres($config->phID);
				tools::__adodb('exec',$q,true,$this->db);
				$up=move_uploaded_file($file['tmp_name'],  "{$this->PhotoGalleryRoot}".tools::__mres($config->pgID,false,true)."_".tools::__link($file['name']) );
			}else{
				$up = false;
			}
		}

	}
	
	protected function zablokujOdblokujZdjecie($phID_){
		$phStatus = tools::__adodb('getOne',"SELECT phStatus FROM ".PGPHOTOS." WHERE phID = '{$phID_}'",true,$this->db);
		$phStatus = ($phStatus) ? 0 : 1;
		$q__ = "UPDATE ".PGPHOTOS." SET phStatus = '{$phStatus}' WHERE phID = ".tools::__mres($phID_);
		tools::__adodb('exec',$q__,true,$this->db);
	}

	protected function zablokujOdblokujGalerie($pgID_){
		$pgStatus = tools::__adodb('getOne',"SELECT pgStatus FROM ".PGCATEGO." WHERE pgID = '{$pgID_}'",true,$this->db);
		$pgStatus = ($pgStatus) ? 0 : 1;
		$q__ = "UPDATE ".PGCATEGO." SET pgStatus = '{$pgStatus}' WHERE pgID = ".tools::__mres($pgID_);
		tools::__adodb('exec',$q__,true,$this->db);
	}
	
	protected function zapiszDanePlikuPhotoGallery($phID = null){
		global $config;
		
		if(is_array($config->phNazwa)){
			foreach ($config->phNazwa as $lang => $photoNazwa) {
				$q__ = "SELECT COUNT(*) FROM ".PGPHOTOS." a 
					LEFT JOIN ".PGPHOTLA." b ON b.phID = a.phID 
					WHERE b.phLang = '{$lang}' AND a.phID = '{$phID}'";
				$istnieje = tools::__adodb('getOne',$q__,true,$this->db);
				if($istnieje == 1){
					$q__ = "UPDATE ".PGPHOTLA." SET phNazwa = ".tools::__mres($photoNazwa)." , 
						phUrl = ".tools::__mres($config->phUrl)." 
						WHERE phID = ".tools::__mres($phID)." AND phLang = ".tools::__mres($lang);
					tools::__adodb('exec',$q__,true,$this->db);	
				}else{
					$q__ = "INSERT INTO ".PGPHOTLA." (phID,phLang,phNazwa,phUrl) 
					VALUES (".tools::__mres($phID).",'{$lang}',".tools::__mres($photoNazwa).",".tools::__mres($config->phUrl)." )";
					tools::__adodb('exec',$q__,true,$this->db);		
				}
			}
			
		}else{
			$q__ = "UPDATE ".PGPHOTLA." SET phNazwa = ".tools::__mres($config->phNazwa).",
				phUrl = ".tools::__mres($config->phUrl)." 
				WHERE phID = ".tools::__mres($phID)." AND phLang = ".tools::__mres($config->phLang);
			tools::__adodb('exec',$q__,true,$this->db);
		}	

		if(is_array($config->phOpis)){
				foreach ($config->phOpis as $lang => $Opis__) {
					$q__ = "SELECT COUNT(*) FROM ".PGPHOTOS." a 
						LEFT JOIN ".PGPHOTLA." b ON b.phID = a.phID 
						WHERE b.phLang = '{$lang}' AND a.phID = '{$phID}'";
					$istnieje = tools::__adodb('getOne',$q__,true,$this->db);
					if($istnieje == 1){
						$q__ = "UPDATE ".PGPHOTLA." SET phOpis = ".tools::__mres($Opis__)."
							WHERE phID = ".tools::__mres($phID)." AND phLang = ".tools::__mres($lang);
						tools::__adodb('exec',$q__,true,$this->db);	
					}else{
						$q__ = "INSERT INTO ".PGPHOTLA." (phID,phLang,phOpis) 
						VALUES (".tools::__mres($phID).",'{$lang}',".tools::__mres($Opis__).")";
						tools::__adodb('exec',$q__,true,$this->db);		
					}
				}
			}
	}
	
	protected function usunZdjeciePG($phID_){
		$q = "SELECT phFile FROM ".PGPHOTOS." a WHERE a.phID = '{$phID_}'" ;
		$file_ = tools::__adodb("getOne",$q,true,$this->db);

		tools::__adodb("exec","DELETE FROM ".PGPHOTLA." WHERE phID = '{$phID_}'",true,$this->db);
		$is_deleted = tools::__adodb("exec","DELETE FROM ".PGPHOTOS." WHERE phID = '{$phID_}'",true,$this->db);
		if ($is_deleted){			
			$this->usunPlikiZdjecia($file_);
		}
	}
	
	
	protected function usunPlikiZdjecia($file_){
			$__thumbs = $this->pobierzListePlkowGalerii($this->PhotoGalleryRoot);
	
			foreach ($__thumbs as $__thumb){
				$__is_del = $this->usunPlikiZDysku($__thumb);
			}
			
			$__is_del = $this->usunPlikiZDysku("{$this->PhotoGalleryRoot}{$file_}");
	}
	
	protected function usunZdjeciaGalerii($pgID_){
		$phFiles_ = tools::__adodb("getAll","SELECT phID,phFile FROM ".PGPHOTOS." a WHERE a.pgID = '{$pgID_}'",true,$this->db);
		tools::__adodb("exec","DELETE FROM ".PGCATEGO." WHERE pgID = '{$pgID_}'",true,$this->db);
		tools::__adodb("exec","DELETE FROM ".PGCATELA." WHERE pgID = '{$pgID_}'",true,$this->db);
		foreach ($phFiles_ as $key => $file_) {			
			tools::__adodb("exec","DELETE FROM ".PGPHOTLA." WHERE phID = '{$file_['phID']}'",true,$this->db);
			$is_deleted = tools::__adodb("exec","DELETE FROM ".PGPHOTOS." WHERE phID = '{$file_['phID']}'",true,$this->db);
			if ($is_deleted){				
			 	$__thumbs = $this->pobierzListePlkowGalerii($this->PhotoGalleryRoot);
		
				foreach ($__thumbs as $__thumb){
					$__is_del = $this->usunPlikiZDysku($__thumb);
				}			
				$__is_del = $this->usunPlikiZDysku("{$this->PhotoGalleryRoot}{$file_['phFile']}");
			}
		}
	}
	
	protected function pobierzListePlkowGalerii($target){
		global $files,$file_;
		$exceptions=array('.','..');
		$pattern="({$file_['phFile']}(.*).thumb$)";
		if (!$sourcedir=@opendir($target)) return false;
		$i=0;
		while(false!==($sibling=readdir($sourcedir))){
			if(!in_array($sibling,$exceptions)){
				$object=str_replace('//','/',$target.'/'.$sibling);
				if(is_dir($object)){
					$this->pobierzListePlkowGalerii($object);
				}
				
				if(is_file($object) && preg_match($pattern,$object)){
					$files[$i] = $object;
				}
				$i++;
			}
		}
		closedir($sourcedir);
		return $files;	
	}
	
	protected function usunPlikiZDysku($__file){
		try {
			$ret = array();
			if(file_exists($__file)){
				$result = @unlink($__file);
				$ret[0] = (!$result) ? false : true;
				$ret[1] = (!$result) ? "$__file został usunięty." : 'Error: file '.$__file. ' not deleted.';
			}else{
				$ret[0] = false;
				$ret[1] = 'Error: file '.$__file. ' not exists.';
			}
			return $ret;
		}catch ( Exception  $e ){
			$ret[0] = false;
			$ret[1] = $e->getMessage();	
			return $ret;		
		}
	}
}